package com.hongyan.widget;

import com.hongyan.config.MainFrameConfig;
import com.hongyan.main.SwingMainFrame;

import javax.swing.*;
import javax.swing.table.TableCellEditor;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.EventObject;

public class ButtonGradeEditor extends AbstractCellEditor implements TableCellEditor, ActionListener {

    protected JButton button;

    private JTable table;
    private String lable;
    private TableButtonClick tableButtonClick;

    public ButtonGradeEditor(String lable, JTable table, TableButtonClick tableButtonClick) {
        button = new JButton();
        this.table = table;
        this.lable = lable;
        this.tableButtonClick = tableButtonClick;
        button.setActionCommand(lable);
        button.addActionListener(this);
        button.setBorderPainted(false);
    }

    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
        if (isSelected) {
            button.setForeground(table.getSelectionForeground());
            button.setBackground(table.getSelectionBackground());
        } else {
            button.setForeground(table.getForeground());
            button.setBackground(UIManager.getColor("Button.background"));
        }
        button.setText((lable == null) ? "" : lable);
        return button;
    }

    @Override
    public Object getCellEditorValue() {
        return lable;
    }

    @Override
    public boolean isCellEditable(EventObject e) {

        return true;
    }

    @Override
    public void actionPerformed(ActionEvent e) {

        fireEditingStopped();
        String id = (String) table.getValueAt(table.getSelectedRow(), 0);

        SwingMainFrame swingMainFrame = MainFrameConfig.getSwingMainFrame();
        String grade = (String) JOptionPane.showInputDialog(swingMainFrame, "学生提交内容为：\n"+(String) table.getValueAt(table.getSelectedRow(), 7)+"\n请输入成绩", "打分", JOptionPane.PLAIN_MESSAGE, null, null, "");
        if (grade != null) {
            tableButtonClick.onClick(1, id, grade);
        }
    }
}
